import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Observable } from 'rxjs/observable';
import { Subscription } from 'rxjs';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

import { Product, ProductService, Comment } from '../share/product.service';
import { getFormatDate } from '../util/date-util';
import { WebscoketService } from '../share/webscoket.service';

const initRating = 5;

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
export class ProductDetailComponent implements OnInit {

  private imgUrl: string;
  private product: Product;
  private comments: Comment[] = new Array<Comment>();
  // 新的评论星级，默认5星
  private newRating = initRating;
  // 新的评论内容，默认为空
  private newComment = '';
  private isCommentHidden: Boolean = true;

  private isWatched = false; // 是否关注商品
  private currentBid: number; // 当前报价

  private subscription: Subscription;

  constructor(
    private activatedRoute: ActivatedRoute,
    private productService: ProductService,
    private webscoketService: WebscoketService
  ) { }

  ngOnInit() {
    this.imgUrl = 'http://placehold.it/820x230';
    let proId: number = this.activatedRoute.snapshot.params['proId'];
    // this.product = this.productService.getProduct(proId);
    // 后边需要product的属性，所以用Observable是不合适的，后边同理
    this.productService.getProduct(proId).subscribe(product => {
      this.product = product;
      this.currentBid = product.price;
    });
    // this.comments = this.productService.getCommentByProductId(proId);
    this.productService.getCommentByProductId(proId).subscribe(comments => {
      this.comments = comments;
      // 重新计算商品的评分
      this.product.rating = this.getNewProductRating();
    });
  }

  /**
   * 添加评论
   */
  addComment() {
    this.isCommentHidden = true;
    let newComment = new Comment(0, this.product.id, getFormatDate(new Date()), '可爱圆', this.newRating, this.newComment);
    this.comments.unshift(newComment);
    // 重置评论区域
    this.newComment = '';
    this.newRating = initRating;
    // 重新计算商品的评分
    this.product.rating = this.getNewProductRating();
  }

  /**
   * 获取商品新的评分
   */
  getNewProductRating(): number {
    return this.comments.reduce((previousValue: number, currentValue: Comment) => {
      return previousValue + currentValue.rating;
    }, 0) / this.comments.length;
  }

  /**
   * 设置是否关注
   */
  watchProduct() {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.isWatched = false;
      this.subscription = null;
    } else {
      this.isWatched = true;
      this.subscription = this.webscoketService.createObservableSocket2('ws://localhost:8087', this.product.id)
        .subscribe(
          products => {
            console.log('products:', products);
            products = JSON.parse(products);
            console.log(typeof products);
            let product = products.find(p => p.productId === this.product.id);
            this.currentBid = product.bid;
          }
        );
    }
  }

}
